package com.demo.fragmentdemo

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

/**
 * A simple [Fragment] subclass.
 * Use the [Fragment1.newInstance] factory method to
 * create an instance of this fragment.
 */
class Fragment1 : Fragment() {
    override fun onAttach(context: android.content.Context) {
        super.onAttach(context)
        Log.d(TAG, "onAttach() - Fragment1 附加到上下文")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "onCreate() - Fragment1 创建")
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d(TAG, "onCreateView() - Fragment1 创建视图")
        
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_1, container, false)

        // 添加Fragment2到容器中
        if (savedInstanceState == null) {
            childFragmentManager.beginTransaction()
                .replace(R.id.fragment2_container, Fragment2())
                .commit()
        }
        
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d(TAG, "onViewCreated() - Fragment1 视图创建完成")
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart() - Fragment1 开始")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume() - Fragment1 恢复")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause() - Fragment1 暂停")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop() - Fragment1 停止")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d(TAG, "onDestroyView() - Fragment1 销毁视图")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy() - Fragment1 销毁")
    }

    override fun onDetach() {
        super.onDetach()
        Log.d(TAG, "onDetach() - Fragment1 分离")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        Log.d(TAG, "onHiddenChanged() - Fragment1 隐藏状态变化: ${if (hidden) "隐藏" else "显示"}")
    }

    companion object {
        private const val TAG = "Fragment1_Lifecycle"

        @JvmStatic
        fun newInstance() = Fragment1()
    }
}